package com.pony.iphone.controller;
import com.pony.iphone.dto.BaseResponse;
import com.pony.iphone.utils.AppHttpCodeEnum;
import com.pony.iphone.utils.R;
import com.theokanning.openai.Usage;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
    @RequestMapping("/api/test")
    public class TestController {

        @Autowired
        private OpenAiService openAiService;

        /**
         * 测试千问API连接
         */
        @GetMapping("/qwen-connection")
        public R testQWenConnection() {
            try {
                Map<String, Object> result = new HashMap<>();

                // 测试调用
                List<ChatMessage> messages = List.of(
                        new ChatMessage(ChatMessageRole.USER.value(), "Hello, respond with just 'OK'")
                );

                ChatCompletionRequest request = ChatCompletionRequest.builder()
                        .model("qwen-turbo")
                        .messages(messages)
                        .maxTokens(5)
                        .build();

                long startTime = System.currentTimeMillis();
                ChatCompletionResult response = openAiService.createChatCompletion(request);
                long responseTime = System.currentTimeMillis() - startTime;

                String answer = response.getChoices().get(0).getMessage().getContent();
                Usage usage = response.getUsage();

                result.put("status", "SUCCESS");
                result.put("response", answer);
                result.put("responseTime", responseTime + "ms");
                result.put("tokensUsed", usage.getTotalTokens());
                result.put("endpointUsed", "默认OpenAI端点");

                return R.error(AppHttpCodeEnum.ERROR)
                        .message("API测试成功")
                        .data(result);

            } catch (Exception e) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("status", "FAILED");
                errorResult.put("error", e.getMessage());
                errorResult.put("endpointUsed", "默认OpenAI端点");

                return R.error(AppHttpCodeEnum.ERROR)
                        .message("API测试失败: " + e.getMessage())
                        .data(errorResult);
            }
        }

    @GetMapping("/deepseek-connection")
    public ResponseEntity<BaseResponse<String>> testDeepSeek() {
        try {
            List<ChatMessage> messages = List.of(
                    new ChatMessage(ChatMessageRole.USER.value(), "Hello, respond with just 'OK'")
            );

            ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .model("deepseek-chat")
                    .messages(messages)
                    .maxTokens(5)
                    .build();

            ChatCompletionResult result = openAiService.createChatCompletion(request);
            String answer = result.getChoices().get(0).getMessage().getContent();

            return ResponseEntity.ok(BaseResponse.success("DeepSeek连接成功: " + answer));

        } catch (Exception e) {
            return ResponseEntity.status(500)
                    .body(BaseResponse.error("DeepSeek连接失败: " + e.getMessage()));
        }
    }

    /**
     * 获取网络信息
     */
    @GetMapping("/network-info")
    public ResponseEntity<BaseResponse<Map<String, Object>>> getNetworkInfo() {
        try {
            log.info("获取网络信息");
            Map<String, Object> info = new HashMap<>();

            // 获取本地网络信息
            info.put("localHostAddress", InetAddress.getLocalHost().getHostAddress());
            info.put("localHostName", InetAddress.getLocalHost().getHostName());

            // 获取公网IP（通过第三方服务）
            String publicIP = getPublicIP();
            info.put("publicIP", publicIP);

            // 测试网络连通性
            info.put("deepseekReachable", testReachability("api.deepseek.com"));
            info.put("openaiReachable", testReachability("api.openai.com"));

            return ResponseEntity.ok(BaseResponse.success("网络信息", info));

        } catch (Exception e) {
            return ResponseEntity.status(500)
                    .body(BaseResponse.error("获取网络信息失败: " + e.getMessage()));
        }
    }

    private String getPublicIP() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.getForObject("https://httpbin.org/ip", String.class);
            // 解析JSON获取IP
            return response;
        } catch (Exception e) {
            return "无法获取: " + e.getMessage();
        }
    }

    private boolean testReachability(String host) {
        try {
            return InetAddress.getByName(host).isReachable(5000);
        } catch (Exception e) {
            return false;
        }
    }

    @GetMapping("/deepseek-apikey")
    public R testApiKey() {
        try {
            Map<String, Object> result = new HashMap<>();

            // 简单测试请求
            List<ChatMessage> messages = List.of(
                    new ChatMessage(ChatMessageRole.USER.value(), "Say 'OK' only")
            );

            ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .model("deepseek-chat")
                    .messages(messages)
                    .maxTokens(5)
                    .build();

            long startTime = System.currentTimeMillis();
            ChatCompletionResult response = openAiService.createChatCompletion(request);
            long responseTime = System.currentTimeMillis() - startTime;

            String answer = response.getChoices().get(0).getMessage().getContent();

            result.put("status", "SUCCESS");
            result.put("response", answer);
            result.put("responseTime", responseTime + "ms");
            result.put("apiKeyStatus", "VALID");

            return R.success(AppHttpCodeEnum.SUCCESS).message("API Key 测试成功").data(result);

        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("status", "FAILED");
            errorResult.put("apiKeyStatus", "INVALID");
            errorResult.put("error", e.getMessage());

            // 分析错误类型
            if (e.getMessage().contains("401") || e.getMessage().contains("auth")) {
                errorResult.put("suggestion", "API Key 无效，请重新生成");
            } else if (e.getMessage().contains("timeout")) {
                errorResult.put("suggestion", "网络超时，请增加超时时间");
            } else {
                errorResult.put("suggestion", "检查网络连接和API Key");
            }

            return R.success(AppHttpCodeEnum.ERROR).message("API Key 测试失败").data(errorResult);
        }
    }

    @GetMapping("/deepseek-network")
    public ResponseEntity<BaseResponse<Map<String, Object>>> debugDeepSeekNetwork() {
        try {
            Map<String, Object> result = new HashMap<>();

            // 测试网络连通性
            result.put("deepseekPing", pingHost("api.deepseek.com"));
            result.put("deepseekConnect", testConnect("api.deepseek.com", 443));
            result.put("dnsResolve", resolveDNS("api.deepseek.com"));

            // 测试其他AI服务
            result.put("zhipuPing", pingHost("open.bigmodel.cn"));
            result.put("moonshotPing", pingHost("api.moonshot.cn"));

            // 系统网络信息
            result.put("javaNetworking", testJavaNetworking());

            return ResponseEntity.ok(BaseResponse.success("DeepSeek 网络诊断", result));

        } catch (Exception e) {
            return ResponseEntity.status(500)
                    .body(BaseResponse.error("网络诊断失败: " + e.getMessage()));
        }
    }

    private String pingHost(String host) {
        try {
            Process process = Runtime.getRuntime().exec("ping -c 3 " + host);
            return process.waitFor() == 0 ? "REACHABLE" : "UNREACHABLE";
        } catch (Exception e) {
            return "ERROR: " + e.getMessage();
        }
    }

    private String testConnect(String host, int port) {
        try (java.net.Socket socket = new java.net.Socket(host, port)) {
            return "CONNECTED";
        } catch (Exception e) {
            return "FAILED: " + e.getMessage();
        }
    }

    private String resolveDNS(String host) {
        try {
            InetAddress[] addresses = InetAddress.getAllByName(host);
            return Arrays.stream(addresses)
                    .map(InetAddress::getHostAddress)
                    .collect(Collectors.joining(", "));
        } catch (Exception e) {
            return "FAILED: " + e.getMessage();
        }
    }

    private Map<String, Object> testJavaNetworking() {
        Map<String, Object> info = new HashMap<>();
        try {
            info.put("proxyHost", System.getProperty("http.proxyHost"));
            info.put("proxyPort", System.getProperty("http.proxyPort"));
            info.put("networkInterfaces", getNetworkInterfaces());
            return info;
        } catch (Exception e) {
            info.put("error", e.getMessage());
            return info;
        }
    }

    private List<String> getNetworkInterfaces() {
        try {
            return Collections.list(java.net.NetworkInterface.getNetworkInterfaces())
                    .stream()
                    .map(java.net.NetworkInterface::getDisplayName)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            return List.of("Error: " + e.getMessage());
        }
    }
}